/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.video;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.async.MediaStoreVideoScannerTask;
import com.phonebooksharing.android.provider.PhonebookSharing.Sync;
import com.phonebooksharing.android.util.GalleryUtilities;
import com.phonebooksharing.android.util.GeneralUtils;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.IOUtilities;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.android.widgets.drawable.FastBitmapDrawable;
import com.phonebooksharing.android.widgets.view.CrossableItem;
import com.phonebooksharing.dto.GenericTransferDTO;
import com.phonebooksharing.dto.gallery.VideoGalleryItem;

@SuppressWarnings("unchecked")
public class VideoGalleryNewActivity extends ListActivity {
    private VideoGalleryListAdapter adapter;
    private View emptyView;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        
        setContentView(R.layout.list_layout_with_empty);
        
        emptyView = findViewById(R.id.empty);
        ((TextView)emptyView.findViewById(android.R.id.text1)).setText("Your Image Gallery is empty\n" +
                                                        "You're not sharing any picture");
        
        final ListView lv = getListView();
        
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CrossableItem<VideoGalleryItem> c = (CrossableItem<VideoGalleryItem>)adapter.getItem(position);
                Uri uri = Uri.parse(c.item.videoUri);
                
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(uri);
                startActivity(i);
            }
        });
        
        adapter = new VideoGalleryListAdapter(VideoGalleryNewActivity.this, lv);
        adapter.checkListener = checkListener;

        lv.addFooterView(adapter.loading, null, false);
        lv.setAdapter(adapter);
        
        new LoadDataTask(lv).execute(this);
    }
    
    private ArrayList<CrossableItem> checkList = new ArrayList<CrossableItem>();
    protected View.OnClickListener checkListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            ImageView iv = (ImageView)v.findViewById(R.id.check);
            CrossableItem vh = (CrossableItem)v.getTag();
            
            if(!vh.isCrossed) {
                iv.setImageState(new int[] { android.R.attr.state_checked }, true);
                iv.setTag("1");
                checkList.add(vh);
                vh.isCrossed = true;
            } else {
                iv.setImageState(new int[] { }, true);
                iv.setTag("0");
                checkList.remove(vh);
                vh.isCrossed = false;
            }
            
            final int s = checkList.size();
            if(s == 1) {//display actions
                showActionPanel();
            } else if (s == 0) {//display actions
                hideActionPanel();
            }
        }
    };
    
    private View actionsPanel;
    private boolean shown;
    private void showActionPanel() {
        View v = actionsPanel;
        if (shown) return;
        if (v == null) {
//            v = ((View) getParent().getParent()).findViewById(R.id.dash_actions);
            v = ((ViewStub)findViewById(R.id.actionStub)).inflate();
        }
        v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in));
        v.setVisibility(View.VISIBLE);
        //setup button archive
        Button b1 = (Button)v.findViewById(android.R.id.button1);
        b1.setText("Start Sharing");
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new InternalManageTask(checkList).execute();
//                startActivityForResult(new Intent(ImageGalleryNewActivity.this, GroupSelectionActivity.class), 0);
            }
        });
        
        v.findViewById(android.R.id.button2).setVisibility(View.INVISIBLE);
        actionsPanel = v;
        shown = true;
    }
    
    private void hideActionPanel() {
        actionsPanel.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out));
        actionsPanel.setVisibility(View.GONE);

        shown = false;
    }
    
    class InternalManageTask extends NetworkHandlerTask<Void, Void, Void> {
        private ArrayList<CrossableItem> checkList;
        public InternalManageTask(ArrayList<CrossableItem> checkList) {
            this.checkList = checkList;
        }
        
        private ProgressDialog d;
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            d = new ProgressDialog(VideoGalleryNewActivity.this);
            d.setTitle("Sharing Video");
            d.setMessage("Please wait while loading...");
            d.setIndeterminate(true);
            d.setCancelable(true);
            d.show();
        }
        
        @Override
        protected Void doInBackground(Void... params) {
            ArrayList<CrossableItem> cl = checkList;
            ArrayList<VideoGalleryItem> list = new ArrayList<VideoGalleryItem>();
            VideoGalleryItem igi;
            for (CrossableItem<VideoGalleryItem> ci : cl) {
                igi = ci.item;
                igi.dateGmt = GeneralUtils.getGmtTimeInMilis();
                list.add(igi);
            }
            
            GenericTransferDTO gt = new GenericTransferDTO();
            gt.authItem = Global.authItem;
            gt.items2 = list;
            
            String url = String.format(Global.PROFILE_SERVLET_URL, "ms" /*ac*/, "avg" /*q*/);
            try {
                ArrayList<VideoGalleryItem> ids = (ArrayList<VideoGalleryItem>)doNetworkPost(url, gt);
                File tempFile = null;
                FastBitmapDrawable f;
                for (VideoGalleryItem ig : ids) {
                    url = String.format("http:" + Global.VIDEO_SERVLET_URL, "uv" /*ac*/, ig.videoID /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/, ig.mimeType /*mt*/, "" /*w*/, "" /*h*/);
                    GalleryUtilities.uploadBinaryStream(url, new File(ig.devicePath));

                    f = GalleryUtilities.getFromVideoThumbCache(ig.videoID);
                    
                    if(f != null) {
                        tempFile = IOUtilities.getExternalFile(System.currentTimeMillis() + ".dat");
    //                    IOUtilities.add2collection(tempFile.getAbsolutePath());
                        IOUtilities.storeExternalBitmap(f.getBitmap(), tempFile);
                    }

                    if(tempFile != null) {
                        url = String.format("http:" + Global.VIDEO_SERVLET_URL, "utv" /*ac*/, ig.videoID /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/, "image/jpeg" /*mt*/, "" /*w*/, "" /*h*/);
                        GalleryUtilities.uploadBinaryStream(url, tempFile);
                        tempFile.delete();
                    } else {
                        url = String.format(Global.VIDEO_SERVLET_URL, "utv" /*ac*/, ig.videoID /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/, "image/jpeg" /*mt*/, "" /*w*/, "" /*h*/);
                        doNetworkPost(url, Global.authItem);
                    }
                }
                
                //update all the processing sync to OK
                ContentResolver cr = getContentResolver();
                
                ContentValues cv = new ContentValues();
                cv.put(Sync.SYNC_STATUS, Sync.STATUS_SUCCESS);
                cr.update(Sync.CONTENT_URI, cv, Sync.SYNC_TYPE + " = " + Sync.SYNC_TYPE_VIDEO + " AND " + Sync.SYNC_STATUS + " = " + Sync.STATUS_PROCESSING, null);
                
                publishProgress();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            d.dismiss();
            Toast.makeText(VideoGalleryNewActivity.this, "Your Image has been successfully uploaded!", Toast.LENGTH_LONG).show();
            finish();
        }
    }
    
    class LoadDataTask extends MediaStoreVideoScannerTask {
        ListView lv;
        
        LoadDataTask(ListView lv) {
            this.lv = lv;
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(ArrayList<VideoGalleryItem>... values) {
            super.onProgressUpdate(values);
            ArrayList<VideoGalleryItem> list = values[0];
//            ContentResolver cr = getContentResolver();
            ArrayList<CrossableItem<VideoGalleryItem>> photos = new ArrayList<CrossableItem<VideoGalleryItem>>();
            Geocoder g = new Geocoder(VideoGalleryNewActivity.this);
//            Cursor ct;
            
            for(VideoGalleryItem l : list) {
                
//                ct = MediaStore.Images.Thumbnails.queryMiniThumbnail(cr, l.deviceID, 1, new String[]{Thumbnails.DATA, Thumbnails.WIDTH, Thumbnails.HEIGHT});
                try {
//                    if(ct != null && ct.moveToFirst()) {
////                        ig.title = "<" + ct.getString(1) + " x " + ct.getString(2) + ">";
//                        l.photoThumbUri = Uri.parse(ct.getString(0)).toString();
//                        l.width = ct.getInt(1);
//                        l.height = ct.getInt(2);
//                        
                    Bitmap b = GalleryUtilities.createVideoThumbnail(l.videoUri);
                    if(b != null) GalleryUtilities.addToVideoThumbCache(l.videoID, b);
                    
                    if(!TextUtils.isEmpty(l.videoLatitude) && !TextUtils.isEmpty(l.videoLongitude)) {
                        double latitude  = new Double(l.videoLatitude),
                               longitude = new Double(l.videoLongitude);
                        Address a; 
                        try {
                            List<Address> aList = g.getFromLocation(latitude, longitude, 1);
                            if(aList != null && aList.size() > 0) {
                                a = aList.get(0);
                                l.whereAt = a.getLocality() + " - " + a.getCountryName();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    photos.add(new CrossableItem<VideoGalleryItem>(l));
                } finally {
//                    CloseableUtil.safeClose(ct);
//                    ct = null;
                }
            }
            adapter.items = photos;
        }

        @Override
        public void onPostExecute(Void void1) {
            super.onPostExecute(void1);
            lv.removeFooterView(adapter.loading);
            if(adapter.items.size() == 0) {
                lv.setEmptyView(emptyView);
            } else {
                adapter.notifyDataSetChanged();
            }
        }
    }
}
